package cn.fldong.controller;

import cn.fldong.model.Score;
import cn.fldong.service.ScoreService;
import cn.fldong.service.impl.ScoreServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/scores")
public class ScoreServlet extends HttpServlet {
    private ScoreService scoreService;

    @Override
    public void init() throws ServletException {
        scoreService = new ScoreServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String action = request.getParameter("action");
        if (action == null) action = "list";

        try {
            switch (action) {
                case "list":
                    listScores(request, response);
                    break;
                case "addPage":
                    request.getRequestDispatcher("/WEB-INF/views/score/add.jsp").forward(request, response);
                    break;
                case "add":
                    addScore(request, response);
                    break;
                case "editPage":
                    editPage(request, response);
                    break;
                case "update":
                    updateScore(request, response);
                    break;
                case "delete":
                    deleteScore(request, response);
                    break;
                case "search":
                    searchScores(request, response);
                    break;
                default:
                    listScores(request, response);
            }
        } catch (SQLException e) {
            e.printStackTrace();
            request.setAttribute("errorMsg", "系统错误：" + e.getMessage());
            request.getRequestDispatcher("/WEB-INF/views/error.jsp").forward(request, response);
        }
    }

    private void listScores(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        List<Score> scores = scoreService.getAllScores();
        request.setAttribute("scores", scores);
        request.getRequestDispatcher("/WEB-INF/views/score/list.jsp").forward(request, response);
    }

    private void addScore(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String scoreId = request.getParameter("scoreId");
        String studentId = request.getParameter("studentId");
        String courseId = request.getParameter("courseId");
        String scoreValueStr = request.getParameter("scoreValue");
        BigDecimal scoreValue = new BigDecimal(scoreValueStr);
        int obj=Integer.parseInt(scoreId);
        if (scoreService.scoreExists(studentId, courseId)) {
            request.setAttribute("errorMsg", "该学生的这门课程成绩已存在");
            Score score = new Score();

            score.setScoreId(obj);
            score.setStudentId(studentId);
            score.setCourseId(courseId);
            score.setScore(scoreValue);
            request.setAttribute("score", score);
            request.getRequestDispatcher("/WEB-INF/views/score/add.jsp").forward(request, response);
            return;
        }

        Score score = new Score();
        score.setScoreId(obj);
        score.setStudentId(studentId);
        score.setCourseId(courseId);
        score.setScore(scoreValue);
        score.setGrade(scoreService.calculateGrade(scoreValue));

        boolean success = scoreService.addScore(score);
        if (success) {
            request.setAttribute("successMsg", "成绩添加成功");
            listScores(request, response);
        } else {
            request.setAttribute("errorMsg", "成绩添加失败");
            request.setAttribute("score", score);
            request.getRequestDispatcher("/WEB-INF/views/score/add.jsp").forward(request, response);
        }
    }

    private void editPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String scoreId = request.getParameter("scoreId");
        Score score = scoreService.getScoreById(scoreId);
        request.setAttribute("score", score);
        request.getRequestDispatcher("/WEB-INF/views/score/edit.jsp").forward(request, response);
    }

    private void updateScore(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String scoreId = request.getParameter("scoreId");
        String studentId = request.getParameter("studentId");
        String courseId = request.getParameter("courseId");
        String scoreValueStr = request.getParameter("scoreValue");
        BigDecimal scoreValue = new BigDecimal(scoreValueStr);
        int obj1=Integer.parseInt(scoreId);
        // 获取原始成绩信息以检查学生ID和课程ID是否变更
        Score originalScore = scoreService.getScoreById(scoreId);
        if (!originalScore.getStudentId().equals(studentId) || !originalScore.getCourseId().equals(courseId)) {
            if (scoreService.scoreExists(studentId, courseId)) {
                request.setAttribute("errorMsg", "该学生的这门课程成绩已存在");
                Score score = new Score();

                score.setScoreId(obj1);
                score.setStudentId(studentId);
                score.setCourseId(courseId);
                score.setScore(scoreValue);
                request.setAttribute("score", score);
                request.getRequestDispatcher("/WEB-INF/views/score/edit.jsp").forward(request, response);
                return;
            }
        }

        Score score = new Score();
        score.setScoreId(obj1);
        score.setStudentId(studentId);
        score.setCourseId(courseId);
        score.setScore(scoreValue);
        score.setGrade(scoreService.calculateGrade(scoreValue));

        boolean success = scoreService.updateScore(score);
        if (success) {
            request.setAttribute("successMsg", "成绩更新成功");
            listScores(request, response);
        } else {
            request.setAttribute("errorMsg", "成绩更新失败");
            request.setAttribute("score", score);
            request.getRequestDispatcher("/WEB-INF/views/score/edit.jsp").forward(request, response);
        }
    }

    private void deleteScore(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String scoreId = request.getParameter("scoreId");
        boolean success = scoreService.deleteScore(scoreId);

        if (success) {
            request.setAttribute("successMsg", "成绩删除成功");
        } else {
            request.setAttribute("errorMsg", "成绩删除失败");
        }

        listScores(request, response);
    }

    private void searchScores(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String studentId = request.getParameter("studentId");
        String courseId = request.getParameter("courseId");

        List<Score> scores;
        if (studentId != null && !studentId.isEmpty()) {
            scores = scoreService.getScoresByStudentId(studentId);
        } else if (courseId != null && !courseId.isEmpty()) {
            scores = scoreService.getScoresByCourseId(courseId);
        } else {
            scores = scoreService.getAllScores();
        }

        request.setAttribute("scores", scores);
        request.setAttribute("searchStudentId", studentId);
        request.setAttribute("searchCourseId", courseId);
        request.getRequestDispatcher("/WEB-INF/views/score/list.jsp").forward(request, response);
    }
}